import React, { useEffect, useLayoutEffect, useState } from 'react';
import { Col, Row } from 'antd';
import { Card } from 'antd';
import { Button, Checkbox, Form, Input } from 'antd';
import { Select, Modal } from 'antd';
import { Graph } from "@antv/x6";
import { useSearchParams } from '@umijs/max';
import type { FormInstance } from 'antd';

import Color from "@/components/Color/Color"
import { SketchPicker } from 'react-color';
import ChooseColor from './ChooseColor/ChooseColor';

const AddPort: React.FC = (props) => {
    const formRef = React.createRef<FormInstance>();//用于创建ref
    let graph: Graph;
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };
    // const [portParams, setPortParams] = useState
    //     ()
    useEffect(() => {

        graph = new Graph({
            container: document.getElementById("container") as HTMLElement,
            width: 800,
            height: 600,
            background: {
                color: "#F2F7FA",
            },
        });

        graph.addNode({
            id: 'element',
            x: 240,
            y: 60,
            width: 100,
            height: 180,
            attrs: {
                body: {
                    fill: '#f5f5f5',
                    stroke: '#d9d9d9',
                    strokeWidth: 1,
                },
                text: {
                    "fontSize": 14,
                    "fill": "#000000",
                    "refX": 0.5,
                    "refY": 0.5,
                    "textAnchor": "middle",
                    "textVerticalAnchor": "middle",
                    "fontFamily": "Arial, helvetica, sans-serif",
                    "text": "元件"
                },
            },
            ports: [
                {
                    id: 'port1',
                    attrs: {
                        circle: {
                            magnet: true,
                            r: 5,
                            stroke: '#31d0c6',
                            fill: '#fff',
                            strokeWidth: 2,
                        },
                    },
                },
            ],
        });
        // 在 useEffect 函数中返回一个清除函数
        return () => {
            graph.dispose(); // 销毁 Graph 实例
        };
    }, []);

    const [form] = Form.useForm();
    form.setFieldsValue({
        Name: '端口111',
    });
    // 开始渲染
    const onFinish = (values: any) => {
        console.log('开始渲染', values)
        console.log('color', strokeColor, backgroundColor)
        console.log(graph)
        let node = graph.getNodes().find(x => x.id == 'element');
        if (node) {
            // setPortParams()
            // const defaultParams = { Shape: 'circle', R: 4, 'Magnet': 'circle', Stroke: '#000000', StrokeWidth: '2', Fill: ' #FF000000' }
            //查看是否有读卡填充颜色
            const defaultParams = { Shape: 'circle', R: 4, 'Magnet': 'circle', Stroke: '#000000', StrokeWidth: '2', Fill: ' #FF000000' }
            for (let key in values) {
                if (values[key] === undefined) {
                    values[key] = defaultParams[key]
                }
            }
            console.log('更新后', values)
            // node.setPortProp('port1', 'position', {
            //     name: values['Position'],
            // })
            // node.portProp('port1', 'position', {
            //     name: values['Position'],
            // })

            node.setPortProp('port1', ["attrs", values['Shape']], {
                r: values['R'],
                fill: values['Fill'],
                stroke: values['Stroke'],
                magnet: values['Magnet'],
                strokeWidth: values['StrokeWidth'],
            });

            // node.portProp('port1', "attrs/circle/r", parseInt(values.r));
        }
    };
    //Modal弹窗开关
    const [isModalOpen, setIsModalOpen] = useState(true);
    // 控制fill颜色
    const [backgroundColor, setBackgroundColor] = useState('');
    //控制线条颜色
    const [strokeColor, setstrokeColor] = useState('');

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        setIsModalOpen(false);
        props.CloseAdd()
    };

    const handleCancel = () => {
        setIsModalOpen(false);
        props.CloseAdd()
    };

    //重置
    const onReset = () => {
        formRef.current?.resetFields();
    };
    return (
        <Modal title="新建端口模型" width="1600px"
            open={isModalOpen}//通过这个bool值打开新建规则 来自于点击按钮
            onOk={handleOk} onCancel={handleCancel}>
            <Row gutter={16}>
                <Col className="gutter-row" span={10}>
                    <Card title="端口可视化配置参数">
                        <Form
                            name="basic"
                            labelCol={{ span: 10 }}
                            wrapperCol={{ span: 20 }}
                            style={{ maxWidth: 800 }}
                            initialValues={{ remember: true }}
                            onFinish={onFinish}//我们点击渲染后进行的操作
                            onFinishFailed={onFinishFailed}// 渲染失败
                            autoComplete="off"
                            ref={formRef}//这个作为传递值的接口
                            form={form}
                        >
                            <Form.Item
                                label="端口名"
                                name="Name"
                                rules={[{ required: true, message: '请输入端口名' }]}
                            // initialValue={'端口1'}
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                label="能源系统类型"
                                name="SystemTypeId"
                                rules={[{ required: true, message: '请输入系统类型' }]}
                                initialValue="powersystem"
                            >

                                <Select
                                    defaultValue="powersystem"
                                    options={[
                                        { value: 'powersystem', label: '电力系统' },
                                        { value: 'heatingsystem', label: '供热系统' },
                                        { value: 'coolingsystem', label: '供冷系统' },
                                        { value: 'gassystem', label: '天然气系统' },
                                        { value: 'informationsystem', label: '信息系统' },
                                    ]}
                                />
                            </Form.Item>
                            <Form.Item
                                label="端口位置"
                                name="Position"
                            // initialValues={{ Position: 'left' }}
                            >
                                <Select
                                    // defaultValue="左"
                                    options={[
                                        { value: 'top', label: '上' },
                                        { value: 'bottom', label: '下' },
                                        { value: 'left', label: '左' },
                                        { value: 'right', label: '右' },
                                    ]}
                                />
                            </Form.Item>
                            <Form.Item
                                label="端口形状"
                                name="Shape"
                            // initialValues={{ Position: 'left' }}
                            >
                                <Select
                                    options={[
                                        { value: 'circle', label: '圆形' },
                                    ]}
                                />
                            </Form.Item>
                            <Form.Item
                                label="R角数值"
                                name="R"
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                label="是否自动吸附x"
                                name="Magnet"
                            >
                                <Select
                                    options={[
                                        { value: true, label: '是' },
                                        { value: false, label: '否' },
                                    ]}
                                />
                            </Form.Item>
                            <Form.Item
                                label="线条颜色"
                                name="Stroke"
                            >
                                {/* <Color
                                    defaultColor={strokeColor}
                                    align={'right'}
                                    setColor={(hex: string) => { setstrokeColor(hex) }}
                                /> */}
                                <ChooseColor></ChooseColor>
                            </Form.Item>
                            <Form.Item
                                label="线条宽度"
                                name="StrokeWidth"
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                label="内部填充色"
                                name="Fill"
                            >
                                <Color
                                    defaultColor={backgroundColor}
                                    align={'right'}
                                    setColor={(hex: string) => { console.log('gra', graph), setBackgroundColor(hex), console.log(graph) }}
                                />

                            </Form.Item>


                            {/* <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 8, span: 16 }}>
                                <Checkbox>Remember me</Checkbox>
                            </Form.Item> */}

                            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                <Button type="primary" htmlType="submit">
                                    渲染视图
                                </Button>

                                <Button htmlType="button" onClick={onReset}>
                                    重置参数
                                </Button>
                            </Form.Item>

                        </Form>
                    </Card>
                </Col>
                <Col className="gutter-row" span={14}>
                    <Card title="端口渲染效果">
                        <div style={{ height: 600 }}>
                            <div id="container"></div>
                        </div>
                    </Card>
                </Col>
            </Row>
        </Modal>

    );
};
export default AddPort;

